//Main CSS Starts HERE
jsURL = function (file) {
    return ASSETS_URL + 'js/' + file + '.js';
}
function loadCss(url) {
    var link = document.createElement("link");
    link.type = "text/css";
    link.rel = "stylesheet";
    link.href = ASSETS_URL + 'css/' + url + '.css';
    document.getElementsByTagName("head")[0].appendChild(link);
}
require([jsURL('global.min'), jsURL('jquery.noty.min')], function () {
    $(function () {
        var item_width = false;
        if (typeof(Storage) !== "undefined") {
            item_width = localStorage.item_width;
        }
        var loading_html = '<i class="fa fa-refresh fa-spin"></i> ';
        if ($(document).width() > 800)
            $('.dropdown-toggle').dropdownHover();
        var grid_container = {
            container_width: false,
            item_width: false,
            items_per_row: false,
            total_items: false,
            block: false,
            container: false,
            item: false,
            item_path: false,
            display_non_equal_rows: false,
            init: function (block, container, item, display_non_equal_rows) {
                this.block = block;
                this.container = container;
                this.item = item;
                this.display_non_equal_rows = display_non_equal_rows;
                this.item_path = this.block + ' ' + this.container + ' ' + this.item;
                this.grid_data();
                grid_container.grid_data();
            },
            cleanUpdata: function () {
                $(this.item_path).removeAttr('style');
            },
            grid_data: function () {
                this.cleanUpdata();
                this.container_width = $(this.block).width();
                this.item_width = $(this.item_path).outerWidth(true);
                this.total_items = $(this.item_path).length;
                this.items_per_row = Math.ceil(this.container_width / this.item_width);
                $(this.item_path).css({
                    width: (this.container_width / this.items_per_row)
                })
                if (typeof(Storage) !== "undefined") {
                    if (item_width != this.container_width / this.items_per_row)
                        this.set_itemWidth(this.container_width / this.items_per_row, this.items_per_row);
                    item_width = this.container_width / this.items_per_row;
                    localStorage.setItem("item_width", item_width);
                }
                if (!this.display_non_equal_rows)
                    this.removeLastRow();
            },
            removeLastRow: function () {
                var slice = this.total_items - (Math.floor(this.total_items / this.items_per_row) * this.items_per_row)
                if (slice && this.total_items > this.items_per_row) {
                    $(this.item_path).slice(-slice).css('display', 'none');
                }
                $(this.block + ' ' + this.container).removeAttr('style')
            },
            set_itemWidth: function (width, items_per_row) {
                $.post(BASEURL + 'js/itemWidth', {width: width, per_row: items_per_row}, function (r) {
                    console.log(r)
                });
            }
        }
        if ($('.grid_container_block').length) {
            $('.grid_container_block').waitForImages(function () {
                $('.grid_container_block').each(function () {
                    grid_container.init($(this).data('block'), $(this).data('container'), $(this).data('item'), $(this).data('non_equal_rows'));
                })
                $(window).resize(function () {
                    $('.grid_container_block').each(function () {
                        grid_container.init($(this).data('block'), $(this).data('container'), $(this).data('item'), $(this).data('non_equal_rows'));
                    })
                })
            });
        }
        var resolution_list = {
            init: function () {
                if ($('.resolution_group').length) {
                    var res_width = screen.width;
                    var res_height = screen.height;
                    if ($('.selected_resolution').length) {
                        res_width = $('.selected_resolution').data('width');
                        res_height = $('.selected_resolution').data('height');
                    }
                    var inList = $('.resolution_group li[data-size="' + res_width + 'x' + res_height + '"]');
                    if (inList.length) {
                        inList.addClass('active');
                        $('.' + inList.data('group')).trigger('click')
                    }
                }
                if ($('.not_found_res').length) {
                    $('.not_found_res').each(function () {
                        $($(this).data('target')).remove();
                    })
                }
            }
        }
        resolution_list.init();

        var category_list = {
            selected_category: false,
            init: function () {
                if ($('.categories_list').length) {
                    $('#g_0').metisMenu();
                    if ($('.active_category').length) {
                        this.selected_category = JSON.parse($('.active_category').html());
                        $('.active_category').remove();
                        this.fix_active_category();
                    }
                }
            },
            fix_active_category: function () {
                var count = (this.selected_category.length) - 1;
                var find = '.categories_list ';
                $.each(this.selected_category, function (i, e) {
                    find += '.' + e + ' ';
                    if (count == i) {
                        if ($(find).hasClass('has-child')) {
                            $(find + ' > a').trigger('click');
                            $(find + ' > ul > li > a').first().addClass('selected');
                        } else {
                            $(find + ' > a').addClass('selected');
                        }
                        return;
                    }
                    $(find + ' > a').trigger('click');
                })
            }
        }
        category_list.init();

        var login_required = function () {
            userLogged = false;
            noty({text: 'Please Login In', type: 'warning'})
        }


        $('[data-toggle="tooltip"]').tooltip();


        $('.next_prev a').on('click', function () {
            $('.next_prev .loading').removeClass('hide');
        })
        var Hash = $('.WallHashID').text();
        //On Vote Click
        $('.votes').on('click', '.voteup,.votedown', function () {
            if (!userLogged) {
                noty({text: $(this).data('guest_msg'), type: 'warning'})
                return false;
            }
            noty({text: loading_html + $(this).data('loading_msg')})
            $.post(BASEURL + 'js/ajax_vote', {hash: Hash, type: ($(this).hasClass('voteup') ? 'voteup' : 'votedown')}, function (r) {
                $.noty.closeAll();
                noty({text: r.msg, type: r.type})
                $('.votes .voteup .text').text(r.vote_status['vote_up'])
                $('.votes .votedown .text').text(r.vote_status['vote_down'])
            }, 'json')
        })

        $('.toggle_favorite').on('click', function () {
            $.noty.closeAll();
            if (Hash) {
                if (!userLogged) {
                    noty({text: $(this).data('guest_msg'), type: 'warning'})
                    return false;
                }
            }
            if ($(this).attr('data-added') == 1) {
                noty({text: loading_html + $(this).data('loading_msg_remove')})
            } else {
                noty({text: loading_html + $(this).data('loading_msg_add')})
            }
            $.post(BASEURL + 'js/ajax_favourite', {hash: Hash}, function (r) {
                $.noty.closeAll();
                noty({text: r.msg, type: r.type})
                $('.toggle_favorite').attr('data-added', r.status);
                if (r.status) {
                    $('.toggle_favorite').html('<i class="fa fa-heart"></i>');
                    $('#total_favourite_count').text(parseInt($('#total_favourite_count').text()) + 1)
                } else {
                    $('.toggle_favorite').html('<i class="fa fa-heart-o"></i>');
                    $('#total_favourite_count').text(parseInt($('#total_favourite_count').text()) - 1)
                }
            }, 'json')
        })

        if ($('.FLASH_ERROR').length) {
            noty({text: $('.FLASH_ERROR').html(), type: 'warning'})
        }
        if ($('.FLASH_MSG').length) {
            noty({text: $('.FLASH_MSG').html(), type: 'notification'})
        }

        if ($('.res_' + screen.width + 'x' + screen.height).length) {
            $('.res_' + screen.width + 'x' + screen.height).addClass('active');
        }

        if ($('.search_available_res').length) {
            if ($('.dl_links').data('width') >= screen.width && $('.dl_links').data('height') >= screen.height) {
                $('.search_available_res').each(function (i, e) {
                    $(e).attr('href', $(e).attr('href').replace('{R_WIDTH}', screen.width).replace('{R_HEIGHT}', screen.height)).removeClass('hide')
                })
            } else {
                $('.dl_links').remove();
                $('.dl_links_error').removeClass('hide');
            }
        }

        $('.starting_download').on('click', function () {
            noty({text: $(this).data('msg'), type: 'success'})
        })

        if ($('.screen_width').length)
            $('.screen_width').html(screen.width);
        if ($('.screen_height').length)
            $('.screen_height').html(screen.height);

        if ($('#comment_form_submit #guest_name').length)
            $('#comment_form_submit #guest_name').val(localStorage.getItem("guest_name"))
        if ($('#comment_form_submit #guest_email').length)
            $('#comment_form_submit #guest_email').val(localStorage.getItem("guest_email"))

        $('#comment_form_submit').on('submit', function (e) {
            if (typeof(Storage) !== "undefined") {
                if ($('#comment_form_submit #guest_name').length)
                    localStorage.setItem("guest_name", $('#comment_form_submit #guest_name').val());
                if ($('#comment_form_submit #guest_name').length)
                    localStorage.setItem("guest_email", $('#comment_form_submit #guest_email').val());
            }
            e.preventDefault();
            $('#submit_comment').button('loading')
            $.post($(this).attr('action'), $(this).serialize(), function (r) {
                if (r.error) {
                    noty({text: r.error, type: 'error'});
                }
                if (r.captcha)
                    Recaptcha.reload();
                if (r.success) {
                    $.noty.closeAll();
                    noty({text: r.success, type: 'success'});
                    $('#comment_text').val('');
                }
                $('#submit_comment').button('reset')

                if (r.html) {
                    $('.comment_data').prepend(r.html);
                }

            }, 'json')
        })

        $('.load_more_comments').on('click', function () {
            $('.load_more_comments').button('loading')
            $.post($(this).data('link'), {offset: $(this).attr('data-offset')}, function (r) {
                $('.load_more_comments').attr('data-offset', r.offset);
                var total_comments = parseInt($('.comment_heading .count').text());
                if (total_comments <= r.offset) {
                    $('.load_more_comments').addClass('hide');
                }
                if (r.html) {
                    $('.comment_data').append(r.html);
                }
                $('.load_more_comments').button('reset')
            }, 'json')
        })


        var last_click_report = false;
        $('.comment_data').on('click', '.report_comment', function () {
            if (!userLogged) {
                login_required();
                return;
            }

            $('#comment_id_selected').text($(this).attr('data-comment-id'));
            $('.comment_id_val').val($(this).attr('data-comment-id'));

            if (last_click_report && last_click_report != $(this).attr('data-comment-id')) {
                $('#report_modal #your_msg').val('');
            }

            $('#report_modal').modal('show');
            last_click_report = $(this).attr('data-comment-id');
        })
        $('.report_this').on('click', function () {
            if (!userLogged) {
                login_required();
                return;
            }
            $(this).button('loading');
            $.post($(this).data('ajax-url'), $('#report_modal').find('input,textarea').serialize(), function (r) {
                if (r.login_required)
                    login_required();
                if (r.error) {
                    noty({text: r.error, type: 'error'});
                }
                if (r.success) {
                    $.noty.closeAll();
                    noty({text: r.success, type: 'success'});
                    $('#your_msg').val('');
                    $('#report_modal').modal('hide');
                    $('#comment_' + r.id + ' .reported_msg').removeClass('hide');
                }
                $('.report_this').button('reset');
            }, 'json')
        })


        $('.global_msg .submit').click(function () {
            var global_msg_btn = $(this);
            global_msg_btn.button('loading');
            $.post($(this).data('ajax-url'), {global: $(this).data('global')}, function (r) {
                global_msg_btn.button('reset');
                window.location.reload();
            })
        })


        var search_color_function = function () {
            if ($('.color_pallet').length) {
                require([jsURL('jquery.minicolors.min')], function () {
                    loadCss('minicolors.min');
                    $('.color_picker .html5_color').minicolors({
                        change: function (hex, opacity) {
                            if (!hex) return;
                            try {
                                $('.color_picker .show_hash .value').html(hex);
                                $('.color_picker .show_hash .clear_color').removeClass('hide');
                                $('input.append_hash').val(hex.replace('#', ''));
                            } catch (e) {
                            }
                        }
                    });
                    $('.color_pallet').on('click', function () {
                        $('.color_picker .html5_color').minicolors('show');
                    })
                })
            }


            $('.clear_color').on('click', function () {
                $('.color_picker .show_hash .value').html('');
                $('.color_picker .show_hash .clear_color').addClass('hide');
                $('input.append_hash').val('');
            })

            $('.search_form').submit(function () {
                $(this).find(":input,select").filter(function () {
                    return !this.value;
                }).attr("disabled", "disabled");
            })
        }
        search_color_function();


        if ($('.crop_image_target').length) {
            require([jsURL('jquery.Jcrop.min')], function () {
                loadCss('jcrop.min');
                var crop_image_width = $('.crop_image_target').data('width');
                var crop_image_height = $('.crop_image_target').data('height');
                $('.crop_image_target').Jcrop({
                    onChange: showCoords,
                    onSelect: showCoords,
                }, function () {
                    this.animateTo([100, 100, 400, 300]);
                    this.setOptions({
                        allowSelect: false,
                        minSize: [ crop_image_width, crop_image_height ],
                        aspectRatio: crop_image_width / crop_image_height
                    });
                });
                function showCoords(c) {
                    $('#x').val(c.x);
                    $('#y').val(c.y);
                    $('#w').val(c.w);
                    $('#h').val(c.h);
                }
            });
        }


        $('.upload_cover').on('click', function () {
            var btn = $(this).button('loading');
            $.post(BASEURL + 'js/upload_cover', $('.cover_s_data').find('input').serialize(), function (r) {
                btn.button('reset');
                if (r.redirect) {
                    if (confirm(r.redirect_msg)) {
                        window.location.href = r.redirect;
                    }
                }
                if (r.success)
                    noty({text: r.success, type: 'success'});

                if (r.approve_url) {
                    $('.approve_link a').attr('href', r.approve_url);
                    $('.approve_link').removeClass('hide');
                    $('.upload_cover').hide()
                }
            }, 'json')
        })

        $('.upload_by_click').click(function () {
            $('.tab_data > div').addClass('hide');
            $('.tab_data #' + $(this).val()).removeClass('hide');
        })


        $('.optional_data').click(function () {
            localStorage.setItem("optional_data", $(this).is(':checked'));
            if ($(this).is(':checked')) {
                $('#optional_data').removeClass('hide')
            } else {
                $('#optional_data').addClass('hide')
            }
        })

        var optional_data = localStorage.getItem("optional_data");
        if(optional_data == "true" && $('#optional_data').hasClass('hide')){
            $('.optional_data').trigger('click')
        }

        if($('*[data-role="tagsinput"]').length){
            loadCss('bootstrap-tagsinput');
            require([jsURL('bootstrap-tagsinput.min')], function () {
            })
        }

        if($('.redactor_required').length){
            loadCss('redactor.min')
            require([jsURL('redactor.min')], function () {
                $('.redactor_required').redactor();
            })
        }
    })
})
